#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import json

from common.common import check_command_injection
from generaldb.saphana.comm.saphana_const import SaphanaJsonConstant


class Param:
    def __init__(self, param_dict, pid=None):
        if pid is not None:
            self.pid = pid
        self.param_dict = param_dict
        self._username = None
        self._password = None

    @property
    def application(self):
        application = self.get_param_field(SaphanaJsonConstant.APPLICATION)
        return application if application else {}

    @property
    def app_extend_info(self):
        app_extend_info = self.get_param_field(SaphanaJsonConstant.EXTEND_INFO, self.application)
        return app_extend_info if app_extend_info else {}

    @property
    def server_type(self):
        server_type = self.get_param_field(SaphanaJsonConstant.TYPE, self.application)
        return server_type if server_type else SaphanaJsonConstant.TYPE

    @property
    def sub_type(self):
        sub_type = self.get_param_field(SaphanaJsonConstant.SUB_TYPE, self.application)
        return sub_type if sub_type else ""

    @property
    def get_log_path_from_app_env(self):
        log_backup_ext_info = self.get_param_field(SaphanaJsonConstant.APP_ENV).\
            get(SaphanaJsonConstant.EXTEND_INFO, {}).get(SaphanaJsonConstant.LOG_BACKUP_EXT_INFO, "{}")
        if not log_backup_ext_info:
            return ""
        log_backup_ext_info = json.loads(log_backup_ext_info)
        log_path = log_backup_ext_info.get(SaphanaJsonConstant.LOG_BACKUP_PATH, "")
        if check_command_injection(log_path):
            return ""
        return log_path

    @staticmethod
    def get_body_error_param(code: int, body_error: int, message: str, err_params: list = None):
        params = {"code": code, "bodyErr": body_error, "message": message, "bodyErrParams": err_params}
        return params

    def get_param_field(self, field, param_dict=None):
        if param_dict is None:
            param_dict = self.param_dict
        target_value = None
        if not isinstance(param_dict, dict):
            return target_value
        target_value = param_dict.get(field)
        return target_value
